;
(function (call) {
    var main = {
        userInfo: null,
        mapId: "jcybMap",
        areaCode: '',
        disasterCfg: {
            'MFRInfo': '山洪沟', 'GEOInfo': '地灾隐患点', 'VFInfo': '城镇易涝点', 'TOUInfo': '旅游景区', 'HOSInfo': '重点医院', 'PMSInfo': '中小学校',
            'RSVInfo': '山塘水库', 'FEInfo': '易燃易爆场所', 'ODPInfo': '其他易灾场所', 'RPInfo': '灾害责任人', 'DSInfo': '全国气象防灾减灾预警发布设施', 'rawData': '原始数据集'
        },
        siteDetailsCfg: {
            'MFRInfo': {
                mfrName: '山洪沟名称：', lon: '沟口位置经度：', lat: '沟口位置纬度：', mfrHeight: '沟口位置海拔高度：', mfrAddrName: '沟口位置名称：',
                townCode: '影响村镇：', rainfallFactor: '致灾因子(降水)：', waterLineFactor: '致灾因子(水位)：', soilFactor: '致灾因子(土壤)：', rainfallThreshold: '降水阈值：',
                waterLineThreshold: '水位阈值：', soilThreshold: '土壤阈值：', contact: '联系人：', mobilePhone: '联系电话：', stationId: '关联监测站ID：', reportUnitName: '填报单位信息：'
            },
            'GEOInfo': {
                geoName: '地灾点名称：', lon: '位置经度：', lat: '位置纬度：', townCode: '影响村镇：', dmFactor: '诱发因素：', threatPerNum: '威胁人数：',
                economicLoss: '潜在经济损失（万元）：', recordYear: '资料记录年：', rainfallFactor: '致灾因子(降水)：', waterLineFactor: '致灾因子(水位)：', soilFactor: '致灾因子(土壤)：',
                rainfallThreshold: '降水阈值：', waterLineThreshold: '水位阈值：', soilThreshold: '土壤阈值：', respUnit: '防灾责任单位：', respPerson: '防灾责任人：',
                respMobilePhone: '防灾责任人电话：', monitorPerson: '监测人：', monMobilePhone: '监测人电话：', stationId: '关联监测站ID：', reportUnitName: '填报单位信息：'
            },
            'VFInfo': {
                vulnerFloodName: '易涝点名称：', lon: '位置经度：', lat: '位置纬度：', stationId: '关联监测站ID：', contact: '联系人：', mobilePhone: '手机：', rainfallFactor: '致灾因子(降水)：',
                waterLineFactor: '致灾因子(水位)', soilFactor: '致灾因子(土壤)：', rainfallThreshold: '降水阈值：', waterLineThreshold: '水位阈值：', soilThreshold: '土壤阈值：', reportUnitName: '填报单位信息：'
            },
            'TOUInfo': { tourName: '景区名称：', lon: '经度：', lat: '纬度：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
            'HOSInfo': { hospitalName: '医院名称：', hospitalLevel: '医院等级：', lon: '经度：', lat: '纬度：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
            'PMSInfo': { schoolName: '学校名称：', lon: '经度：', lat: '纬度：', schoolType: '学校类型：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
            'RSVInfo': { reservoirName: '水库名称：', lon: '经度：', lat: '纬度：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
            'FEInfo': { flaExpPlaceName: '场所名称：', unit: '场所管理单位：', lon: '经度：', lat: '纬度：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
            'DSInfo': {
                clientID: '终端编号：', factoryID: '厂商编号：', factoryServerID: '厂商服务器编号：', originalClientID: '终端原始编号：', clientStyle: '终端型号：', lon: '经度：',
                lat: '纬度：', address: '终端地址：', clientPerson: '终端负责人：', clientTel: '负责人联系方式：', reportUnitName: '填报单位信息：'
            },
            'RPInfo': {
                perName: '姓名：', unitName: '单位名称：', mobilePhone: '手机：', duty: '职务：', lon: '经度：', lat: '纬度：', reportUnitName: '填报单位信息：'
            },
            'ODPInfo': { name: '场所名称：', department: '场所管理单位：', lon: '经度：', lat: '纬度：', contact: '联系人：', mobilePhone: '电话：', reportUnitName: '填报单位信息：' },
        },
        init: function () {
            this.bindEvt();
            this.initView();
        },
        initView: function () {
            var that = this;
            that.getAreaData();
            $("#modal_account").find("#modal-title span").first().click();
            var userInfo = $("#userInfo").data('info');
            this.userInfo = userInfo;
			if (this.userInfo.roleIds.indexOf('e9b0eaab-f2a3-4f71-9e64-644b255a706c') > -1) {
                $(".data-download, .data-upload").hide();
            }
        },
        // 站点详情展示
        siteDetailsShow: function (data, type) {
            var that = this;
            var content = $($("#stationInfo").html());
            var $closeBtn = $('<div>').addClass('siteCloseBtn').text('×');
            var $stationDetails = $('<div>').addClass('site-details')
            for (var key in that.siteDetailsCfg[data.type]) {
                var $div = $('<div>');
                var $span = $('<span>');
                var $a = $('<a>');
                var name = that.siteDetailsCfg[data.type][key]
                var val = data[key];
                $div.append($span.text(name)).append($a.text(val).attr('title', val));
                $stationDetails.append($div)
            }
            content.append($stationDetails).append($closeBtn)
            return content[0].outerHTML;
        },
        //弹出框内容
        alert: function (info) {
            $.dialogMaster({
                "type": 'tip',
                "info": info
            });
        },
        // 获取区域数据
        getAreaData: function () {
            var that = this;
            $.getJSON(api.internal.business.getAreaData, function (res) {
                if (res.isSuccess) {
                    var data = res.data;
                    that.dataDisplay(data);
                    that.dataDown(data);
                    that.dataUpload(data)
                }
            });
        },
        // 数据展示页面
        dataDisplay: function (data) {
            var $area = $('.area-list').empty().append(`<li><label>全部</label><i></i></li>`);
            var code = Number(this.userInfo.userAreaCode);
            for (var i = 0; i < data.length; i++) {
                var areaObj = data[i];
                if (areaObj.areaId != 120) {
                    var updateTime = areaObj.updateTime || '无';
                    if (updateTime) updateTime = updateTime.substr(0, 16);
                    var $div = $(`<li title="更新时间：${updateTime}"><label>${areaObj.areaName}</label><i></i></li>`)
                    if (code == areaObj.areaId) {
                        $div = $(`<li class="active" title="更新时间：${updateTime}"><label>${areaObj.areaName}</label><i></i></li>`)
                    }
                    $div.data('area', areaObj);
                    $area.append($div);
                }
            }
            $('.area-list li.active').click();
        },
        initDisasterType: function (areaCode) {
            var that = this;
            var $disasterType = $('.disaster-type').empty();
            var _json = JSON.stringify(that.disasterCfg);
            var json = JSON.parse(_json);
            if (areaCode != '12') {
                delete json['DSInfo'];
            }
            if (areaCode == 'all') {
                delete json['rawData'];
            }
            for (var key in json) {
                var $div = $(`<li type='${key}'>${json[key]}</li>`);
                $disasterType.append($div);
            }
        },
        // 展示数据下载页面
        dataDown: function (data) {
            var $excel = $('.excel-down').empty();
            var $xml = $('.xml-down').empty();
            for (var i = 0; i < data.length; i++) {
                var areaObj = data[i];
                var li = '<li>' + areaObj.areaName + '</li>'
                var $li = $(li);
                $li.data('area', areaObj);
                $excel.append($li);
            }
            for (var i = 0; i < data.length; i++) {
                var areaObj = data[i];
                var li = '<li>' + areaObj.areaName + '</li>'
                var $li = $(li);
                $li.data('area', areaObj);
                $xml.append($li);
            }
        },
        // 展示数据上传页面
        dataUpload: function (data) {
            var that = this;
            var $company = $('#company').empty();
            $(".upload-people .people").text(that.userInfo.smuser.name);
            for (var i = 0; i < data.length; i++) {
                var areaObj = data[i];
                if (areaObj.areaId != 120) {
                    var code = Number(that.userInfo.userAreaCode);
                    if (code === areaObj.areaId) {
                        $company.append(`<option selected value=${areaObj.areaId}>${areaObj.areaName}</option>`);
                    } else {
                        $company.append(`<option value=${areaObj.areaId}>${areaObj.areaName}</option>`);
                    }
                    if (code === 12) {
                        $company.removeAttr('disabled');
                    } else {
                        $company.attr('disabled', 'disabled');
                    }
                }
            }
        },
        // 获取站点数据
        getSiteData: function (type, areaCode) {
            var that = this;
            var param = {
                time: $("#datepicker .datepicker-date>span").text() + ':00',
                clientStyle: '0,1'
            }
            var url = api.internal.business.getSiteData + areaCode + '/' + type
            if (type != 'DSInfo') {
                $.getJSON(url, function (res) {
                    if (res.isSuccess) {
                        that.getPartSiteData(type, areaCode, res.data)
                    }
                });
            } else {
                url = api.internal.business.getFacilitiesData
                loading.add('#modal_account');
                $.getJSON(url, param, function (res) {
                    loading.remove();
                    if (res.isSuccess) {
                        that.getPartSiteData(type, areaCode, res.data)
                    }
                });
            }
        },
        getPartSiteData: function (type, areaCode, data) {
            var that = this;
            var layerId = 'fzjz-' + areaCode + '-' + type;
            var dataList = data, dataList1 = [], dataList2 = [], dataList3 = [], dataList4 = [], totalDataList = [];
            dataList = dataList.filter(function (data) {
				return $.isNumeric(data.lon) && $.isNumeric(data.lat) && data.areaCode != '120';
			})
            dataList.forEach(function (port, i) {
				if (!$.isNumeric(port.lon) || !$.isNumeric(port.lat)) return;
                port.lat = Number(port.lat)
                port.lon = Number(port.lon)
                port.img_type = 'icon'
                port.type = type
                if (type == 'DSInfo') {
                    if (port.clientStyle == '大喇叭') {
                        if (port.status == '0') {
                            dataList1.push(port)
                        } else {
                            dataList2.push(port)
                        }
                    } else {
                        if (port.status == '0') {
                            dataList3.push(port)
                        } else {
                            dataList4.push(port)
                        }
                    }
                }
            })
            totalDataList.push(dataList1)
            totalDataList.push(dataList2)
            totalDataList.push(dataList3)
            totalDataList.push(dataList4)
            if (dataList.length > 0) {
                if (type == 'DSInfo') {
                    for (var i = 0; i < totalDataList.length; i++) {
                        if (totalDataList[i].length > 0)
                            GIS.Common.showImage(that.mapId, layerId + '-' + i, totalDataList[i], { icon: { src: 'business/jcyb/account/css/images/' + type + i + '.png', width: 24, height: 24, xoffset: 12, yoffset: 12 } });
                    }
                } else {
                    GIS.Common.showImage(that.mapId, layerId, dataList, { icon: { src: 'business/jcyb/account/css/images/' + type + '.png', width: 24, height: 24, xoffset: 12, yoffset: 12 } });
                }
                GIS.MouseEvent.Bind(that.mapId, layerId, function (data) {
                    $('#jcybMap_infowindow_Wrapper').css({ 'width': '0', 'height': '0', 'background': 'transparent', 'border': 'none' })
                    $("#jcybMap_infowindow_outerPointer").hide()
                    return that.siteDetailsShow(data, type);
                }, function (data) {
                    return data.name;
                })
            }
        },
        // excel上传
        excelUpload: function () {
            var that = this;
            var userId = that.userInfo.smuser.iid;
            // userId = 1002
            var areaCode = $("#company").val();
            var name = $("#excel-file").val();
            var hzm = name.substr(name.lastIndexOf(".") + 1);
            if (name == '') {
                alert('请选择需要上传的文件');
            } else if (hzm != "xls" && hzm != 'xlsx') {
                alert('请选择excel格式的文件');
            } else {
                var forData = new FormData();
                forData.append('excel', $('#excel-file')[0].files[0])
                loading.add('#modal_account');
                $.ajax({
                    url: api.internal.business.excelUpload + userId + '/' + areaCode,
                    type: "POST",
                    data: forData,
                    dataType: 'json',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        loading.remove();
                        if (res.isSuccess) {
                            alert("上传成功");
                            $("#file-text").text('').removeAttr('title');
                            $("#excel-file").val('')
                            that.getAreaData();
                        } else {
                            alert("上传失败");
                        }
                    }
                })
            }
        },
        // 删除图层
        deleteLayer: function (id) {
            var layerIds = [];
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf(id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        // excel预览
        productPreview: function (areaCode) {
            $.getJSON(api.internal.business.excelLookup + areaCode, function (res) {
                if (res.isSuccess) {
                    var url = res.data;
                    $("#modal_excel_Preview .modal-body").empty().append(`<iframe id="contentFrame" name="contentFrame" frameborder="0" scrolling="no" src=""></iframe>`)
                    $("#contentFrame").attr("src", "/ioffice/officeView.do?path=" + encodeURI(encodeURI(url)));
                }
            })
        },
        // excel预览弹窗
        excelPreview: function () {
            if ($("#modal_excel_Preview .modal-content").is(':visible')) return;
            if ($("#modal_excel_Preview").is(':hidden')) {
                $("#modal_excel_Preview").show();
                return;
            }
            CafeJS.ModalBox({
                id: 'excel_Preview',
                title: "excel展示",
                width: 1250,
                height: 750,
                m_top: 70,
                m_left: 335,
                hide: false,
                closed: function () {
                }
            });
        },
        // 合并和上传
        mergeFile: function (type) {
            var that = this;
            var userId = that.userInfo.smuser.iid;
            var url = api.internal.business.excelMergeAll + userId + '/' + 120;
            if (type == 1) {
                url = api.internal.business.fptUpload + userId + '/' + 120;
            }
			loading.add();
            $.ajax({
                url: url,
                type: "POST",
                dataType: 'json',
                success: function (res) {
					loading.remove();
                    if (res.isSuccess) {
                        alert(type == 1 ? '上传成功' : '合并成功');
                    } else {
                        alert(type == 1 ? '上传失败' : '合并失败');
                    }
                },
				fail: function(res) {
					loading.remove();
				}
            })
        },
        bindEvt: function () {
            var that = this;
            $("#modal_account").find(".modal-title>span").click(function () {
                $(this).addClass("active").siblings().removeClass("active");
                $(".account-content>li").eq($(this).index()).show().siblings().hide();
            });
            $("#modal_account .close").click(function () {
                $("#modal_account").remove();
                $("#account").removeClass("active");
            });
            $(".area-list").on('click', 'li', function () {
                $(this).addClass("active").siblings().removeClass("active");
                var txt = $(this).find('label').text();
                if (txt == '全部') {
                    that.areaCode = 'all';
                } else {
                    that.areaCode = $(this).data('area').areaId;
                }
                that.deleteLayer('fzjz');
                that.initDisasterType(that.areaCode);
            })
            $(".disaster-type").on('click', 'li', function () {
                var type = $(this).attr('type');
                var areaCode = that.areaCode;
                if (type != 'rawData') {
                    $(this).toggleClass('active');
                    if ($(this).hasClass('active')) {
                        that.getSiteData(type, areaCode);
                    } else {
                        var id = 'fzjz-' + areaCode + '-' + type;
                        that.deleteLayer(id);
                    }
                } else {
                    that.excelPreview()
                    that.productPreview(areaCode);
                }
            })
            $(".excel-down").on('click', 'li', function () {
                var areaCode = $(this).data('area').areaId;
                var url = api.internal.business.excelDownload + areaCode;
                $("#excelIframe").attr("src", url);
            })
            $(".xml-down").on('click', 'li', function () {
                var areaCode = $(this).data('area').areaId;
                var url = api.internal.business.xmlDownload + areaCode;
                $("#xmlIframe").attr("src", url);
            })
            $(".down-template").click(function () {
                var url = api.internal.business.excelTplDownload;
                window.location.href = url;
            })
            $("#excel-file").change(function () {
                var val = $("#excel-file").val()
                $("#file-text").text(val).attr('title', val)
            })
            $(".upload-btn").click(function () {
                that.excelUpload();
            })
            $(".excel-close-btn").click(function () {
                $(".excel-display").hide();
            })
            $("#jcybMap_infowindow_Wrapper").on('click', '.siteCloseBtn', function () {
                $(".stationInfo").remove();
            })
            $("#mergeBtn").click(function () {
                that.mergeFile(0);
            })
            $("#uploadBtn").click(function () {
                that.mergeFile(1);
            })
        },
    };
    if (typeof call === 'function') {
        call(main);
    }
})(function (main) {
    CafeJS.models(['datepicker'], function () {
        main.init();
    });
});